// 路由健全:全局守卫
import router from './router';
// 引入仓库,拿出token
import store from './store';

// to:跳转到的路由对象
// from:跳转前的路由对象
// next 函数,类似于path
// next() next('') next({})
router.beforeEach(async (to, from, next) => {
  //判断用户是否token
  let token = store.state.User.token
  let nickName = store.state.User.nickName
  if (token) {
    // 已登录****(不能再去登录页面和注册页面)
    if (to.path === '/login' || to.path === '/register') {
      next(from.path)
    } else {
      // token可能过期
      if (nickName) {
        next()
      } else {
        try {
         await store.dispatch('checkingToken')
          next()
        } catch (error) {
         await store.dispatch('Userlogout')
         next({path:'/login'})
        }
      }
    }
  } else {
    // 未登录****(所有路由均可跳转)
    if (to.path === '/trade'|| to.path === '/pay' || to.path === '/paysuccess' || to.path === '/center' || to.path === '/center/myorder' || to.path === '/center/teamorder') {
        next({path:'/login',query:{a:from.path}})
    } else {
      next()
    }
  }
})


router.afterEach((to, from) => {
  document.title = `尚品汇★★★${to.meta.title}`
})